const eventModel = require('../models/eventModel');
const logModel = require('../models/logModel'); // 引入日志模型
const customNodeType = require('../models/customNodeType');

// 获取所有事件
async function getAllEvents(req, res, next) {
  try {
    const events = await eventModel.getAllEvents();
    res.json(events);
  } catch (error) {
    next(error);
  }
}

// 获取单个事件
async function getEventById(req, res, next) {
  try {
    const { id } = req.params;
    const event = await eventModel.getEventById(id);
    
    if (!event) {
      return res.status(404).json({
        success: false,
        message: '事件不存在'
      });
    }
    
    res.json(event);
  } catch (error) {
    next(error);
  }
}

// 创建事件
async function createEvent(req, res, next) {
  try {
    const eventData = req.body;
    
    // 基本验证
    if (!eventData.name || !eventData.categoryId) {
      return res.status(400).json({
        success: false,
        message: '缺少必要字段'
      });
    }
    
    // 确保有ID
    if (!eventData.id) {
      eventData.id = `event_${Date.now()}`;
    }
    
    // 确保有创建时间
    if (!eventData.createTime) {
      eventData.createTime = new Date().toLocaleString();
    }
    
    // 确保有节点数组
    if (!eventData.nodes) {
      eventData.nodes = [];
    }
    
    const newEvent = await eventModel.createEvent(eventData);
    
    res.status(201).json(newEvent);
  } catch (error) {
    next(error);
  }
}

// 更新事件
async function updateEvent(req, res, next) {
  try {
    const { id } = req.params;
    const eventData = req.body;
    
    // 基本验证
    if (!eventData.name || !eventData.categoryId) {
      return res.status(400).json({
        success: false,
        message: '缺少必要字段'
      });
    }
    
    const updatedEvent = await eventModel.updateEvent(id, eventData);
    
    if (!updatedEvent) {
      return res.status(404).json({
        success: false,
        message: '事件不存在'
      });
    }
    
    res.json(updatedEvent);
  } catch (error) {
    next(error);
  }
}

// 删除事件
async function deleteEvent(req, res, next) {
  try {
    const { id } = req.params;
    const result = await eventModel.deleteEvent(id);
    
    if (!result) {
      return res.status(404).json({
        success: false,
        message: '事件不存在'
      });
    }
    
    res.json({
      success: true,
      message: '事件删除成功'
    });
  } catch (error) {
    next(error);
  }
}

// 获取分类下的事件
async function getEventsByCategory(req, res, next) {
  try {
    const { categoryId } = req.params;
    const events = await eventModel.getEventsByCategory(categoryId);
    
    res.json(events);
  } catch (error) {
    next(error);
  }
}

// 运行事件
async function runEvent(req, res, next) {
  try {
    const { id } = req.params;
    const event = await eventModel.getEventById(id);
    
    if (!event) {
      return res.status(404).json({
        success: false,
        message: '事件不存在'
      });
    }
    
    // 创建运行开始时间
    const runTime = new Date().toISOString();
    
    // 在实际项目中，这里会有真正的事件运行逻辑
    // 模拟运行结果
    const runResult = {
      success: true,
      message: '事件运行成功',
      eventId: id,
      eventName: event.name,
      startTime: runTime,
      endTime: new Date().toISOString(),
      result: '事件执行完成',
      logs: [
        { type: 'info', message: `开始运行事件: ${event.name}`, timestamp: runTime },
        { type: 'info', message: `正在执行节点流程，共${event.nodes ? event.nodes.length : 0}个节点`, timestamp: new Date().toISOString() },
        { type: 'success', message: `事件执行完成`, timestamp: new Date().toISOString() }
      ]
    };
    
    // 将运行记录保存到日志中
    const logData = {
      id: `log_${Date.now()}`,
      eventId: id,
      runTime: runTime,
      result: runResult.result,
      status: runResult.success ? 'success' : 'failed',
      logs: runResult.logs,
      duration: new Date(runResult.endTime) - new Date(runResult.startTime) // 运行时长(毫秒)
    };
    
    // 保存日志记录
    await logModel.createLog(logData);
    
    res.json(runResult);
  } catch (error) {
    // 如果运行过程中出错，也需要记录日志
    if (req.params.id) {
      try {
        const errorLogData = {
          id: `log_${Date.now()}`,
          eventId: req.params.id,
          runTime: new Date().toISOString(),
          result: error.message || '事件运行出错',
          status: 'error',
          logs: [
            { type: 'error', message: `事件运行错误: ${error.message}`, timestamp: new Date().toISOString() }
          ],
          duration: 0
        };
        
        await logModel.createLog(errorLogData);
      } catch (logError) {
        console.error('保存错误日志失败:', logError);
      }
    }
    
    next(error);
  }
}

// 更新事件数据架构
async function updateEventsSchema(req, res, next) {
  try {
    const updatedCount = await eventModel.updateEventSchema();
    
    res.status(200).json({
      success: true,
      message: `成功更新了 ${updatedCount} 个事件的数据结构`,
      count: updatedCount
    });
  } catch (error) {
    next(error);
  }
}

// 获取引用特定版本的事件
async function getEventsByVersionId(req, res, next) {
  try {
    const { versionId } = req.params;
    const page = parseInt(req.query.page) || 1;
    const pageSize = parseInt(req.query.pageSize) || 10;
    
    const { events, total } = await customNodeType.findEventsByVersionId(
      versionId,
      page,
      pageSize
    );
    
    res.status(200).json({
      success: true,
      events,
      pagination: {
        page,
        pageSize,
        total,
        totalPages: Math.ceil(total / pageSize)
      }
    });
  } catch (error) {
    next(error);
  }
}

// 添加版本引用到事件
async function addVersionReference(req, res, next) {
  try {
    const { eventId } = req.params;
    const { versionId, nodeTypeId } = req.body;
    
    // 验证必要参数
    if (!versionId || !nodeTypeId) {
      return res.status(400).json({
        success: false,
        message: '缺少必要参数：versionId 和 nodeTypeId'
      });
    }
    
    const event = await eventModel.addVersionReference(eventId, versionId, nodeTypeId);
    
    if (!event) {
      return res.status(404).json({
        success: false,
        message: '事件不存在'
      });
    }
    
    res.status(200).json({
      success: true,
      message: '成功添加版本引用',
      event
    });
  } catch (error) {
    next(error);
  }
}

// 从事件中移除版本引用
async function removeVersionReference(req, res, next) {
  try {
    const { eventId, versionId } = req.params;
    
    const event = await eventModel.removeVersionReference(eventId, versionId);
    
    if (!event) {
      return res.status(404).json({
        success: false,
        message: '事件不存在或没有该版本引用'
      });
    }
    
    res.status(200).json({
      success: true,
      message: '成功移除版本引用',
      event
    });
  } catch (error) {
    next(error);
  }
}

module.exports = {
  getAllEvents,
  getEventById,
  createEvent,
  updateEvent,
  deleteEvent,
  getEventsByCategory,
  runEvent,
  updateEventsSchema,
  getEventsByVersionId,
  addVersionReference,
  removeVersionReference
}; 